import React, { useEffect, useRef, useMemo, useState } from 'react';
import styles from './index.module.less';
import FormGroup, { FormListItem } from '@/components/form-group';
import ButtonFooter from '@/components/button-footer';
import { PRICE_TYPE, PRICE_TYPE_LIST } from '@/pages/official-doc/constants';
import { StandardItem } from '@/pages/official-doc/interface';
import { checkMoneyFormat } from '@/utils/form-rules';
import { getMatterStandardUnit } from '@/services/laber-declare';
import { FormatDictData } from '@/utils/formatter';
export interface Props {
  standard: StandardItem;
  handleChange?: (data: StandardItem, type?: 'back') => void;
}

const DocStandard: React.FC<Props> = (props) => {
  const { standard, handleChange } = props;
  const formRef: React.MutableRefObject<any> = useRef();
  const [filterList, setFilterList] = useState(['price', 'minPrice', 'maxPrice']);
  //  请求页面中标准字典的列表
  const [matterStandardUnitList, setMatterList] = useState<Array<any>>([]);
  const getMatterList = async () => {
    const matterData = await getMatterStandardUnit();
    const { list: matterList } = FormatDictData(matterData.data, 'uint', 'meaning');
    setMatterList(matterList);
  };
  useEffect(() => {
    getMatterList();
  }, []);


  const handleOk = async () => {
    let data: StandardItem = await formRef.current.getValues();
    data = {
      ...data,
      priceType: Array.isArray(data.priceType) ? data.priceType[0] : data.priceType,
      unit: data.unit,
      minPrice: data.minPrice || data.price,
      maxPrice: data.maxPrice || data.price
    } as StandardItem;
    formRef.current.resetValues();
    console.log(data);
    handleChange && handleChange(data);
  };

  const checkPrice = (_rule: any, _value: any, callback: any) => {
    const minPrice = Number(formRef.current.getData()['minPrice'] || 0);
    const maxPrice = Number(formRef.current.getData()['maxPrice'] || 0);
    if (maxPrice < minPrice) {
      callback('最高单价必须高于最低单价');
    } else {
      callback();
    }
  };

  const getList = (list: string[]) => {
    const formList: FormListItem[] = [
      {
        valueKey: 'standardName', label: '标准名称', type: 'input',
        options: { rules: [{ required: true, message: '请填写标准名称' }, { whitespace: true, message: '标准名称不能为空' }] },
        cellProps: { maxLength: 64 }
      }, {
        valueKey: 'priceType', label: '标准类型', type: 'radioSelect',
        pickerOptions: PRICE_TYPE_LIST,
        options: {
          rules: [{ required: true, message: '请选择标准类型' }],
          initialValue: (Array.isArray(standard.priceType) ? standard.priceType[0] : standard.priceType) || PRICE_TYPE.FIXED
        },
        cellProps: {
          onChange: (value: number) => {
            console.log('标准类型', value);
            if (value === PRICE_TYPE.FIXED) {
              setFilterList(['minPrice', 'maxPrice']);
            } else if (value === PRICE_TYPE.RANGE) {
              setFilterList(['price']);
            }
          }
        }
      }, {
        valueKey: 'unit', label: '单位', type: 'radioSelect',
        pickerOptions: matterStandardUnitList,
        options: { rules: [{ required: true, message: '请选择单位' }] }
      }, {
        valueKey: 'price', label: '单价', type: 'input',
        options: {
          rules: [
            { required: true, message: '请选择单价' },
            { validator: checkMoneyFormat }
          ]
        },
        cellProps: { type: 'money', moneyKeyboardAlign: 'left', autoAdjustHeight: true, maxLength: 10 }
      }, {
        valueKey: 'minPrice', label: '最低单价', type: 'input',
        options: {
          rules: [
            { required: true, message: '请选择最低单价' },
            { validator: checkPrice },
            { validator: checkMoneyFormat }
          ]
        },
        cellProps: { type: 'money', moneyKeyboardAlign: 'left', autoAdjustHeight: true, maxLength: 10 }
      }, {
        valueKey: 'maxPrice', label: '最高单价', type: 'input',
        options: {
          rules: [
            { required: true, message: '请选择最高单价' },
            { validator: checkPrice },
            { validator: checkMoneyFormat }
          ]
        },
        cellProps: { type: 'money', moneyKeyboardAlign: 'left', autoAdjustHeight: true, maxLength: 10 }
      }, {
        valueKey: 'remark', label: '备注', type: 'input',
        cellProps: { placeholder: '请输入（选填）', maxLength: 200 }
      }
    ];
    return formList.filter((item: FormListItem) => {
      if (list.indexOf(item.valueKey) > -1) {
        return false;
      }
      return true;
    });
  };

  const getListMemo = useMemo(() => getList(filterList), [filterList, matterStandardUnitList]);

  const transformData = (dataSource: StandardItem, list: string[]) => {
    const formatedData = {} as StandardItem;
    // 指定的属性转数组类型（传入值为非数组类型，但是picker组件值必须为数组类型）
    list.forEach((item: string) => {
      if (dataSource[item] !== undefined && !Array.isArray(dataSource[item])) {
        formatedData[item] = [dataSource[item]];
      }
    });
    // 针对price特殊处理
    if (dataSource.minPrice === dataSource.maxPrice) {
      formatedData.price = dataSource.minPrice;
    }
    // 控制表单回填时价格相关控件的显隐
    const priceType = Array.isArray(dataSource.priceType) ? dataSource.priceType[0] : dataSource.priceType;
    if (priceType === PRICE_TYPE.RANGE) {
      setFilterList(['price']);
    } else {
      setFilterList(['minPrice', 'maxPrice']);
    }
    return formatedData;
  };

  useEffect(() => {
    const standardCopy = standard;
    if (Object.keys(standardCopy).length) {
      const formatedData = transformData(standardCopy, ['priceType']);
      // 有没有其他异步实现方式
      setTimeout(() => {
        formRef.current.setValues({ ...standardCopy, ...formatedData });
      }, 0);
    }
  }, [standard]);

  return (
    <div className={styles.wrap}>
      <FormGroup
        ref={formRef}
        formList={getListMemo}
      />
      <ButtonFooter
        data={
          [{
            text: '确定',
            onClick: handleOk
          }]
        }
      />
    </div>
  );
};

export default DocStandard;